package com.ogawa.project8506e.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.view.View
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.ogawa.base.bean.LoadState
import com.ogawa.base.constants.Constants
import com.ogawa.base.mqtt.MqttManager
import com.ogawa.base.utils.SpUtil
import com.ogawa.projectcommon.constants.UrlPathConstant
import com.ogawa.project8506e.R
import com.ogawa.project8506e.adapter.CollectAdapter
import com.ogawa.project8506e.base.Base8506EMqttActivity
import com.ogawa.project8506e.bean.Massage8506EArmchair
import com.ogawa.projectcommon.bean.CollectBean
import com.ogawa.project8506e.viewmodel.CollectViewModel
import com.ogawa.projectcommon.constants.Constant
import com.ogawa.projectcommon.datacollect.DataCollectUtils
import com.ogawa.projectcommon.utils.ProjectSpUtils
import kotlinx.android.synthetic.main.activity_8506_device_main.*

@Route(path = UrlPathConstant.ACTIVITY_8506E_MASSAGE)
class Device8506eDeviceMainActivity : Base8506EMqttActivity(), View.OnClickListener {
    private var pointRes = arrayOf(
        R.drawable.img_poing_16,
        R.drawable.img_poing_15,
        R.drawable.img_poing_14,
        R.drawable.img_poing_13,
        R.drawable.img_poing_12,
        R.drawable.img_poing_11,
        R.drawable.img_poing_10,
        R.drawable.img_poing_9,
        R.drawable.img_poing_8,
        R.drawable.img_poing_7,
        R.drawable.img_poing_6,
        R.drawable.img_poing_5,
        R.drawable.img_poing_4,
        R.drawable.img_poing_3,
        R.drawable.img_poing_2,
        R.drawable.img_poing_1
    )
    private var currentBean: CollectBean = CollectBean()
    private lateinit var adapter: CollectAdapter
    private var auto = 0
    private var health = 0
    private var diy = 0
    private var advance = "0"
    private var type = 0
    private var programName = ""
    private var autoName = ""
    private var healthName = ""
    private var diyName = ""

    companion object {
        const val AUTO = 1
        const val HEALTH = 2
        const val ADVANCE = 3
        const val AI = 4
        lateinit var collectViewModel: CollectViewModel
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_8506_device_main
    }

    override fun initView() {
        super.initView()
        setTitle(getString(R.string.current_chair))
        tv_auto.setOnClickListener(this)
        tv_recommend.setOnClickListener(this)
        tv_health_life.setOnClickListener(this)
        tv_advance.setOnClickListener(this)
        tv_seat_adjust.setOnClickListener(this)
        tv_power.setOnClickListener(this)
        tv_pause.setOnClickListener(this)
        tv_foot_roll.setOnClickListener(this)
        tv_heat.setOnClickListener(this)
        tv_shake.setOnClickListener(this)
        tv_diy.setOnClickListener(this)
        iv_collect.setOnClickListener(this)
        time_view.setFunc(Constants.TIME_SET)
        lev_view_4d.setFunc(Constants._4D_STRENGTH, "47", ProjectSpUtils.getCurDeviceTypeCode())
        lev_view_strength.setFunc(Constants.MASSAGE_STRENGTH, "44", ProjectSpUtils.getCurDeviceTypeCode())
        lev_view_speed.setFunc(Constants.MASSAGE_SPEED, "45", ProjectSpUtils.getCurDeviceTypeCode())
        lev_view_gas.setFunc(Constants.AIR_INTENSITY, "46", ProjectSpUtils.getCurDeviceTypeCode())
        rlv_collect.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
        adapter = CollectAdapter()
        rlv_collect.adapter = adapter
        collectViewModel = ViewModelProviders.of(this).get("collect", CollectViewModel::class.java)
        collectViewModel.loadState.observe(this, Observer {
            when (it) {
                is LoadState.Loading -> {
                    showLoadingDialog(canceledOnTouchOutside = false)
                }
                is LoadState.Fail -> {
                    dismissLoadingDialog()
                    ToastUtils.showShort(it.msg)
                }
                is LoadState.Success -> {
                    iv_collect.isSelected = it.msg == "1"
                    dismissLoadingDialog()
                }
            }
        })
        collectViewModel.collectBeans.observe(this, Observer {
            adapter.setNewData(it)
        })
        collectViewModel.getCollects()
        adapter.setOnItemClickListener { _, _, position ->
            val bean = adapter.data[position]
            when (bean.type) {
                1 -> publish(
                    Constants.AUTO_PROGRAM,
                    "8",
                    bean.program.toString()
                )
                6 -> publish(
                    Constants.LIFE_AUTO_PROGRAM,
                    bean.program.toString()
                )
            }
        }
    }

    override fun onClick(v: View?) {
        if (!isSnExist()) {
            return
        }
        when (v?.id) {
            R.id.tv_auto -> startActivityForResult(
                Intent(this, AutoProgramActivity::class.java),
                AUTO
            )
            R.id.tv_recommend -> startActivityForResult(
                Intent(this, Device8506eAiRecommendActivity::class.java),
                AI
            )
            R.id.tv_health_life -> startActivityForResult(
                Intent(this, Device8506eHealthLifeActivity::class.java),
                HEALTH
            )
            R.id.tv_advance -> startActivityForResult(
                Intent(this, Device8506eAdvanceActivity::class.java),
                ADVANCE
            )
            R.id.tv_seat_adjust -> ARouter.getInstance()
                .build(UrlPathConstant.ACTIVITY_8506E_SEAT_ADJUST)
                .navigation()
            R.id.tv_power -> {
                if (tv_power.isSelected) {
                    publish(Constants.RUNNING_STATUS, "0")
                } else {
                    if (Massage8506EArmchair.getInstance().reset == 1) {
                        publish(Constants.RUNNING_STATUS, "1")
                    } else {
                        ToastUtils.showShort(getString(R.string.movement_resetting_tip))
                    }
                }
            }
            R.id.tv_pause -> {
                if (tv_pause.isSelected) {
                    publish(Constants.RUNNING_STATUS, "3")
                } else {
                    publish(Constants.RUNNING_STATUS, "2")
                }
            }
            R.id.tv_foot_roll -> {
                publish(Constants.FOOT_WHEEL_BUTTON, "3")
                if (tv_power.isSelected) {
                    val switchStatus = if (tv_foot_roll.isSelected) 0 else 1
                    DataCollectUtils.footRollEvent(
                        switchStatus,
                        type,
                        programName,
                        Constants.FOOT_WHEEL_BUTTON + "/3",
                        ProjectSpUtils.getCurDeviceTypeCode()
                    )
                }
            }
            R.id.tv_heat -> {
                publish(Constants.HEAT_BACK_BUTTON, "3")
                if (tv_power.isSelected) {
                    val switchStatus = if (tv_heat.isSelected) 0 else 1
                    DataCollectUtils.warmEvent(
                        "加热",
                        switchStatus,
                        type,
                        programName,
                        Constants.HEAT_BACK_BUTTON + "/3",
                        ProjectSpUtils.getCurDeviceTypeCode()
                    )
                }
            }
            R.id.tv_shake -> publish(Constants.SIT_VIBRATE_BUTTON, "3")
            R.id.tv_diy -> {
                ARouter.getInstance().build(UrlPathConstant.ACTIVITY_8506E_DIY)
                    .navigation()
            }
            R.id.iv_collect -> {
                if (iv_collect.isSelected) {
                    collectViewModel.unCollect(currentBean)
                } else {
                    collectViewModel.collect(currentBean)
                }
            }
        }
    }


    @SuppressLint("SetTextI18n")
    override fun onDeviceStateChange() {
        super.onDeviceStateChange()
        val instance = Massage8506EArmchair.getInstance()
        tv_power.isSelected = instance.runningStatus == 1 || instance.runningStatus == 2
        tv_pause.isSelected = instance.runningStatus == 2
        tv_pause.text =
            if (tv_pause.isSelected) getString(R.string.start) else getString(R.string.pause)
        val deviceStatusBean = instance.deviceStatusBean
        if (deviceStatusBean != null) {
            val autoProgram = deviceStatusBean.functions.autoProgram
            val autoValue = Integer.parseInt(autoProgram.modelValue)
            tv_auto.isSelected = autoValue != 0
            if (auto != autoValue) {
                if (auto != 0) {
                    //自动程序事件收集
                    DataCollectUtils.programChange(
                        Constants.AUTO_PROGRAM + "," + auto.toString(), autoName, 1, false,
                        ProjectSpUtils.getCurDeviceTypeCode()
                    )
                }
                if (autoValue > 0) {//开启程序
                    currentBean.type = 1
                    currentBean.program = autoProgram.modelValue
                    currentBean.programName = autoProgram.itemName
                    iv_collect.visibility = View.VISIBLE
                    val bean = collectViewModel.getCollectBean(1, autoValue)
                    iv_collect.isSelected = bean != null
                    tv_current_program.text =
                        getString(R.string.current_program) + autoProgram.itemName
                    type = 1
                    programName = autoProgram.itemName
                    autoName = autoProgram.itemName
                    //自动程序事件收集
                    DataCollectUtils.programChange(
                        Constants.AUTO_PROGRAM + "," + autoProgram.modelValue,
                        autoProgram.itemName,
                        1,
                        true,
                        ProjectSpUtils.getCurDeviceTypeCode()
                    )
                } else {
                    autoName = ""
                }
                auto = autoValue
            }
            val healthProgram = deviceStatusBean.functions.lifeAutoProgram
            val healthValue = Integer.parseInt(healthProgram.modelValue)
            tv_health_life.isSelected = healthValue != 0
            if (health != healthValue) {
                if (health != 0) {
                    //健康生活事件收集
                    DataCollectUtils.programChange(
                        Constants.LIFE_AUTO_PROGRAM + "," + health.toString(),
                        healthName,
                        1,
                        false,
                        ProjectSpUtils.getCurDeviceTypeCode()
                    )
                }
                if (healthValue > 0) {
                    currentBean.type = 6
                    currentBean.program = healthProgram.modelValue
                    currentBean.programName = healthProgram.itemName
                    iv_collect.visibility = View.VISIBLE
                    val bean = collectViewModel.getCollectBean(6, healthValue)
                    iv_collect.isSelected = bean != null
                    tv_current_program.text =
                        getString(R.string.current_program) + healthProgram.itemName
                    type = 1
                    programName = healthProgram.itemName
                    healthName = healthProgram.itemName
                    DataCollectUtils.programChange(
                        Constants.LIFE_AUTO_PROGRAM + "," + health.toString(),
                        healthName,
                        1,
                        true,
                        ProjectSpUtils.getCurDeviceTypeCode()
                    )
                } else {
                    healthName = ""
                }
                health = healthValue
            }
            val diyProgramKey = deviceStatusBean.functions.diyProgramKey
            val diyIndex = diyProgramKey.modelValue.toInt()
            tv_diy.isSelected = diyIndex > 0
            if (diy != diyIndex) {
                if (diy != 0) {
                    //DIY按摩事件收集
                    DataCollectUtils.programChange(
                        Constants.DIY_PROGRAM + "," + diy.toString(), diyName, 2, false,
                        ProjectSpUtils.getCurDeviceTypeCode()
                    )
                }
                if (diyIndex > 0) {
                    iv_collect.visibility = View.GONE
                    tv_current_program.text =
                        getString(R.string.current_program) + getString(R.string.diy_title)
                    type = 2
                    programName = diyProgramKey.itemName
                    diyName = diyProgramKey.itemName
                    //DIY按摩事件收集
                    DataCollectUtils.programChange(
                        Constants.DIY_PROGRAM + "," + diyProgramKey.modelValue,
                        diyProgramKey.itemName,
                        2,
                        true,
                        ProjectSpUtils.getCurDeviceTypeCode()
                    )
                } else {
                    diyName = ""
                }
                diy = diyIndex
            }
            val advanceProgram = deviceStatusBean.functions.advanceAutoProgram
            val advanceValue = advanceProgram.modelValue
            tv_advance.isSelected = advanceValue != "0"
            if (advance != advanceValue) {
                if (advance != "0") {
                    //高级按摩事件收集
                    DataCollectUtils.programChange(
                        Constants.ADVANCE_AUTO_PROGRAM + "," + advance,
                        "高级按摩",
                        4,
                        false,
                        ProjectSpUtils.getCurDeviceTypeCode()
                    )
                }
                advance = advanceValue
                if (advanceValue != "0") {
                    type = 4
                    programName = advanceProgram.itemName
                    //高级按摩事件收集
                    DataCollectUtils.programChange(
                        advanceProgram.modelValue, advanceProgram.itemName, 4, true,
                        ProjectSpUtils.getCurDeviceTypeCode()
                    )
                }
            }
            lev_view_4d.setProgramInfo(type, programName)
            lev_view_strength.setProgramInfo(type, programName)
            lev_view_speed.setProgramInfo(type, programName)
            lev_view_gas.setProgramInfo(type, programName)
            val min = deviceStatusBean.functions.timeMin.modelValue
            var sec = deviceStatusBean.functions.timeSec.modelValue
            if (sec.length < 2) {
                sec = "0$sec"
            }
            tv_remain_time.text = getString(R.string.remain_time) + min + getString(R.string.minute)
            if (tv_advance.isSelected) {
                iv_collect.visibility = View.GONE
                tv_current_program.text =
                    getString(R.string.current_program) + getString(R.string.advance_massage)
            }
            if (autoValue == 0 && healthValue == 0 && advanceValue == "0" && diyIndex == 0) {//无程序运行
                iv_collect.visibility = View.GONE
                currentBean = CollectBean()
                tv_current_program.text = getString(R.string.current_program)
                tv_remain_time.text = getString(R.string.remain_time)
            }
            lev_view_4d.setLev(Integer.parseInt(deviceStatusBean.functions._4dStreng.modelValue))
            lev_view_strength.setLev(Integer.parseInt(deviceStatusBean.functions.massageStrength.modelValue))
            lev_view_speed.setLev(Integer.parseInt(deviceStatusBean.functions.massageSpeed.modelValue))
            lev_view_gas.setLev(Integer.parseInt(deviceStatusBean.functions.airIntensity.modelValue))
            tv_heat.isSelected =
                Integer.parseInt(deviceStatusBean.functions.heatBackButton.modelValue) == 1
            tv_foot_roll.isSelected =
                Integer.parseInt(deviceStatusBean.functions.footWheelButton.modelValue) == 1
//            tv_shake.isSelected =
//                Integer.parseInt(deviceStatusBean.functions.sitVibrateButton.modelValue) == 1
            iv_gas_shoulder.visibility =
                if (Integer.parseInt(deviceStatusBean.functions.airCellShoulderStatus.modelValue) == 1) View.VISIBLE else View.GONE
            iv_gas_arm.visibility =
                if (Integer.parseInt(deviceStatusBean.functions.airCellHandStatus.modelValue) == 1) View.VISIBLE else View.GONE
            iv_gas_foot.visibility =
                if (Integer.parseInt(deviceStatusBean.functions.airCellFootStatus.modelValue) == 1) View.VISIBLE else View.GONE
            group_gas_leg.visibility =
                if (Integer.parseInt(deviceStatusBean.functions.airCelllegStatus.modelValue) == 1) View.VISIBLE else View.GONE
            iv_gas_hip.visibility =
                if (Integer.parseInt(deviceStatusBean.functions.airCellSeatStatus.modelValue) == 1) View.VISIBLE else View.GONE
//            groupShake.visibility =
//                if (Integer.parseInt(deviceStatusBean.functions.sitVibrateButton.modelValue) == 1) View.VISIBLE else View.GONE
            iv_heat.visibility =
                if (Integer.parseInt(deviceStatusBean.functions.heatBack.modelValue) == 1) View.VISIBLE else View.GONE
            iv_foot_roll.visibility =
                if (Integer.parseInt(deviceStatusBean.functions.footWheel.modelValue) == 1) View.VISIBLE else View.GONE
            iv_point.setImageResource(pointRes[Integer.parseInt(deviceStatusBean.functions.yPos.modelValue)])
            time_view.setTime(Integer.parseInt(deviceStatusBean.functions.timeMin.modelValue))
            adapter.setCurrentProgram(currentBean)
        } else {
            if (auto != 0) {
                //自动程序事件收集
                DataCollectUtils.programChange(
                    Constants.AUTO_PROGRAM + "," + auto,
                    programName,
                    1,
                    false,
                    ProjectSpUtils.getCurDeviceTypeCode()
                )
                auto = 0
            }
            if (health != 0) {
                DataCollectUtils.programChange(
                    Constants.LIFE_AUTO_PROGRAM + "," + health,
                    programName,
                    1,
                    false,
                    ProjectSpUtils.getCurDeviceTypeCode()
                )
                health = 0
            }
            if (diy != 0) {
                //DIY程序事件收集
                DataCollectUtils.programChange(
                    Constants.DIY_PROGRAM + "," + diy,
                    programName,
                    2,
                    false,
                    ProjectSpUtils.getCurDeviceTypeCode()
                )
                diy = 0
            }
            if (advance != "0") {
                //高级按摩事件收集
                DataCollectUtils.programChange(
                    Constants.ADVANCE_AUTO_PROGRAM + "," + advance,
                    programName,
                    4,
                    false,
                    ProjectSpUtils.getCurDeviceTypeCode()
                )
                advance = "0"
            }
            type = 0
            this.programName = ""
            autoName = ""
            healthName = ""
            diyName = ""
            tv_auto.isSelected = false
            tv_advance.isSelected = false
            tv_health_life.isSelected = false
            tv_diy.isSelected = false
            tv_current_program.text = getString(R.string.current_program)
            tv_remain_time.text = getString(R.string.remain_time)
            lev_view_4d.setLev(-1)
            lev_view_strength.setLev(-1)
            lev_view_speed.setLev(-1)
            lev_view_gas.setLev(-1)
            tv_heat.isSelected = false
            tv_foot_roll.isSelected = false
            tv_shake.isSelected = false
            iv_gas_shoulder.visibility = View.GONE
            iv_gas_arm.visibility = View.GONE
            iv_gas_foot.visibility = View.GONE
            group_gas_leg.visibility = View.GONE
//            groupShake.visibility = View.GONE
            iv_heat.visibility = View.GONE
            iv_foot_roll.visibility = View.GONE
            iv_point.setImageResource(0)
            iv_collect.visibility = View.GONE
            currentBean = CollectBean()
            adapter.setCurrentProgram(currentBean)
            lev_view_4d.setProgramInfo(type, this.programName)
            lev_view_strength.setProgramInfo(type, this.programName)
            lev_view_speed.setProgramInfo(type, this.programName)
            lev_view_gas.setProgramInfo(type, this.programName)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        val program = data?.getStringExtra("program")
        when (requestCode) {
            AUTO -> {
                if (program != null && program.isNotEmpty()) {
                    publish(Constants.AUTO_PROGRAM, "8", program)
                }
            }
            HEALTH -> {
                if (program != null && program.isNotEmpty()) {
                    publish(Constants.LIFE_AUTO_PROGRAM, program)
                }
            }
            ADVANCE -> {
                if (program != null && program.isNotEmpty()) {
                    publish(Constants.ADVANCE_AUTO_PROGRAM, "27", program)
                }
            }
            AI -> {
                if (program != null && program.isNotEmpty()) {
                    publish(Constants.AUTO_PROGRAM, "8", program)
                }
            }
        }
    }
    override fun onDestroy() {
        super.onDestroy()
        MqttManager.getInstance().disconnect()
        SpUtil.set(SpUtil.IS_NEED_RE_CONNECT_MQTT, false)
    }
}